<?php

if (!function_exists('venue_getDistanceBuilder')) {
    function venue_getDistanceBuilder($lat, $lng) {
        return "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((". venue_matchLatLng($lat) . " * PI() / 180 - lat * PI() / 180) / 2), 2) + COS(". venue_matchLatLng($lat). " * PI() / 180) * COS(lat * PI() / 180) * POW(SIN((". venue_matchLatLng($lng). " * PI() / 180 - lon * PI() / 180) / 2), 2))) * 1000) AS distance";
    }
}

if (!function_exists('venue_matchLatLng')) {
    function venue_matchLatLng($latlng) {
        $match = "/^\d{1,3}\.\d{1,30}$/";
        return preg_match($match, $latlng) ? $latlng : 0;
    }
}


if (!function_exists('venue_orderNo')) {

    function venue_orderNo()
    {
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}

if (!function_exists('venue_get_distance')){
    /**
     * 根据起点坐标和终点坐标测距离
     * @param  [array]   $from     [起点坐标(经纬度),例如:array(118.012951,36.810024)]
     * @param  [array]   $to     [终点坐标(经纬度)]
     * @param  [bool]    $km        是否以公里为单位 false:米 true:公里(千米)
     * @param  [int]     $decimal   精度 保留小数位数
     * @return [string]  距离数值
     */
    function venue_get_distance($from,$to,$km=true,$decimal=2){
        sort($from);
        sort($to);
        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $distance = $EARTH_RADIUS*2*asin(sqrt(pow(sin( ($from[0]*pi()/180-$to[0]*pi()/180)/2),2)+cos($from[0]*pi()/180)*cos($to[0]*pi()/180)* pow(sin( ($from[1]*pi()/180-$to[1]*pi()/180)/2),2)))*1000;

        if($km){
            $distance = $distance / 1000;
        }

        return round($distance, $decimal);
    }
}

if (!function_exists('venue_generateRandomString')) {
    function venue_generateRandomString($length)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';

        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }

        return $randomString;
    }
}

if (!function_exists('venue_format_dates')) {
    function venue_format_dates($time){
        $t=time()-$time;
        $f=array(
            '31536000'=>'年',
            '2592000'=>'个月',
            '604800'=>'星期',
            '86400'=>'天',
            '3600'=>'小时',
            '60'=>'分钟',
            '1'=>'秒'
        );
        foreach ($f as $k=>$v)    {
            if (0 !=$c=floor($t/(int)$k)) {
                return $c.$v.'前';
            }
        }
        return '一秒前';
    }
}

